package SingleLinkList;


public class LinkListTry <E>{
	private Node<E> head = null;
	private int size =0;
	
	
	//constructor
	
	public LinkListTry(){
		
	}
	
	public void addFirst(E item){
		Node<E> temp = new Node<E>(item,head);
		head = temp;
		size++;
	}
		
	public void addAfter(Node<E> node,E item){
		Node<E> temp = new Node<E>(item,node.next);
		node.next = temp;
		size++;
		
	}
	
	public E removeAfter(Node<E> node){
		Node<E> temp = node.next;
		if (temp != null){
			node.next = temp.next;
			size--;
			return temp.data;
		} else {
			return null;
		}
		
		
	}
	
	public E removeFirst(){
		Node<E> temp = head;
		if(head !=null){
			head = head.next;
		}
		if (temp != null){
			size --;
			return temp.data;
		}else {
			return null;
		}
		
		
	}
		
	//tranversing a single-Linked List ?
	public String toString(){
		Node<E> nodeRef = head;
		StringBuilder result = new StringBuilder();
			while (nodeRef !=null){
				result.append(nodeRef.data);
				
			if (nodeRef.next != null){
				result.append("==>");
				
			}
			nodeRef = nodeRef.next;
		}
		return result.toString();
	}
	
	public Node<E> getNode(int index){
		Node<E> node = head;
		for(int i=0; i<index && node != null;i++){
			node = node.next;
		}
		return node;
	}
	
	public E get(int index){
		if (index <0 ||index >=size){
			throw new IndexOutOfBoundsException(Integer.toString(index));
		}
		Node<E> node = getNode(index);
		return node.data;
	}
	
	public void add(int index, E item){
		if(index < 0||index>size){
			throw new IndexOutOfBoundsException(Integer.toString(index));
		}
		if(index ==0){
			addFirst(item);
		}else{
			Node<E> node = getNode(index-1);
			addAfter(node,item);
		}
	}
	
	//add an item to the end of the list
	public boolean add(E item){
		add(size,item);
		return true;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkListTry test = new LinkListTry();
		test.add(1);
		test.add(5);
		test.add(3);
		test.add(4);
		test.add(2);
//		System.out.println(test.toString());
		test.removeFirst();
		System.out.println(test.toString());
		Node node = test.getNode(2);
		test.removeAfter(node);
		System.out.println(test.toString());
		
		
	}

}
